import { FC, useState } from 'react';
import { Input, Modal, Button, Form, Col, Row } from 'antd';
import * as styles from './style.less';
import { Dispatch } from 'umi';
const { Search } = Input;

interface IUserListForm {
  dispatch: Dispatch;
}
const UserListForm: FC<IUserListForm> = ({ dispatch }) => {
  //把表单的值放入val中
  const [values, setValues] = useState({});

  const getFormValues = (changedFields: any, allFields: any) => {
    // console.log('fileds', allFields);
    let formVal = {};
    allFields.forEach((item: any) => {
      formVal = {
        ...formVal,
        [item.name[0]]: item.value,
      };
    });
    setValues(formVal);
  };

  //表单页面
  const [isModalVisible, setIsModalVisible] = useState(false);

  const showModal = () => {
    setIsModalVisible(true);
  };

  //点击确定的回调 添加用户
  const handleOk = () => {
    //todo 将values通过dispatch传递给effects
    dispatch({
      type: 'userList/addUser',
      values,
    });
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  //搜索用户名
  const onSearch = (value: any) => {
    // console.log('value', value);
    dispatch({
      type: 'userList/getUserList',
      params: {
        query: value,
        pagenum: 1,
        pagesize: 10,
      },
    });
  };
  return (
    <div>
      <Row className={styles.use_list_form}>
        <Col span="5">
          <Search placeholder="请输入用户名" enterButton onSearch={onSearch} />
        </Col>
        <Col>
          <Button type="primary" onClick={showModal}>
            添加用户
          </Button>
          <Modal
            title="添加用户"
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
          >
            <Form
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 24 }}
              onFieldsChange={getFormValues}
            >
              <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: '请输入密码' }]}
              >
                <Input.Password />
              </Form.Item>
              <Form.Item
                label="邮箱"
                name="email"
                rules={[{ message: '请输入邮箱' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="电话"
                name="mobile"
                rules={[{ message: '请输入电话' }]}
              >
                <Input />
              </Form.Item>
            </Form>
          </Modal>
        </Col>
      </Row>
    </div>
  );
};

export default UserListForm;
